package com.cndcare.msc.channelInitializer;

import com.cndcare.msc.protobuf.MessageVo;
import com.cndcare.msc.protobuf.ObjDecoder;
import com.cndcare.msc.protobuf.ObjEncoder;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component(value = "serverChannelInitializer")
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${server.READER_IDLE_TIME_SECONDS}")
    private int READER_IDLE_TIME_SECONDS;

    @Value("${server.WRITER_IDLE_TIME_SECONDS}")
    private int WRITER_IDLE_TIME_SECONDS;

    @Value("${server.ALL_IDLE_TIME_SECONDS}")
    private int ALL_IDLE_TIME_SECONDS;

    @Autowired
    @Qualifier("serverHeartHandler")
    private ChannelInboundHandlerAdapter serverHeartHandler;

    @Autowired
    @Qualifier("otherServerHandler")
    private ChannelInboundHandlerAdapter otherServerHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline p = socketChannel.pipeline();
        //检测空闲必须放在这里 因为pipeline是分顺序加载的
        p.addLast("idleStateHandler", new IdleStateHandler(READER_IDLE_TIME_SECONDS
                , WRITER_IDLE_TIME_SECONDS, ALL_IDLE_TIME_SECONDS, TimeUnit.SECONDS));

        p.addLast(new ObjDecoder(MessageVo.class));
        p.addLast(new ObjEncoder(MessageVo.class));

        //自定义的hanlder
        p.addLast("serverHeartHandler", serverHeartHandler);
//        p.addLast("otherServerHandler", otherServerHandler);
    }
}
